package jsu.hx.lost.Controller;

import jsu.hx.lost.Model.dto.LostItemDTO;
import jsu.hx.lost.Model.vo.PageResult;
import jsu.hx.lost.Service.LostItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/lost")
public class LostController {

    @Autowired
    private LostItemService lostItemService;

    @GetMapping("/all")
    public ResponseEntity<List<LostItemDTO>> getAllLostItems() {
        return ResponseEntity.ok(lostItemService.getAllLostItems());
    }

    @GetMapping("/ById/{id}")
    public ResponseEntity<LostItemDTO> getLostItemById(@PathVariable Long id) {
        LostItemDTO item = lostItemService.getLostItemById(id);
        return item != null ? ResponseEntity.ok(item) : ResponseEntity.notFound().build();
    }

    @PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, Object>> addLostItem(
            @RequestParam String itemName,
            @RequestParam String itemCategory,
            @RequestParam String lostLocation,
            @RequestParam String locate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date lostTime,
            @RequestParam String detailedDescription,
            @RequestParam(required = false) MultipartFile imageFile) {
        Map<String, Object> response = lostItemService.addLostItem(
                itemName, itemCategory, lostLocation,locate, lostTime, detailedDescription, imageFile
        );
        return wrapResponse(response);
    }

    @PutMapping(value = "/update/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, Object>> updateLostItem(
            @PathVariable Long id,
            @RequestParam(value = "image",required = false) MultipartFile imageFile,
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String itemCategory,
            @RequestParam(required = false) String lostLocation,
            @RequestParam(required = false) String locate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date lostTime,
            @RequestParam(required = false) String detailedDescription) {
        Map<String, Object> response = lostItemService.updateLostItem(
                id, imageFile, itemName, itemCategory, lostLocation, locate,lostTime, detailedDescription
        );
        return wrapResponse(response);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteLostItem(@PathVariable Long id) {
        String result = lostItemService.deleteLostItem(id);
        return result.contains("success") ?
                ResponseEntity.ok(result) :
                ResponseEntity.internalServerError().body(result);
    }

    @GetMapping("/myLostItems")
    public ResponseEntity<Map<String, Object>> getMyLostItems() {
        Map<String, Object> response = lostItemService.getMyLostItems();
        return wrapResponse(response);
    }

    @GetMapping("/search")
    public ResponseEntity<List<LostItemDTO>> fuzzySearch(
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String lostLocation,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date lostTime,
            @RequestParam(required = false) String username) {
        return ResponseEntity.ok(lostItemService.fuzzySearch(itemName, lostLocation, lostTime,username));
    }

    @GetMapping("/page")
    public ResponseEntity<PageResult<LostItemDTO>> getLostItemsByPage(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String lostLocation,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date lostTime,
            @RequestParam(required = false) String username,
            @RequestParam(required = false, defaultValue = "id") String sortField,
            @RequestParam(required = false, defaultValue = "DESC") String sortOrder) {

        PageResult<LostItemDTO> result = lostItemService.getLostItemsByPage(
                page, pageSize, itemName, lostLocation, lostTime,
                username, sortField, sortOrder
        );

        return ResponseEntity.ok(result);
    }
    // LostController.java
    @GetMapping("/latest")
    public ResponseEntity<Map<String, Object>> getLatestLostItems(
            @RequestParam(defaultValue = "3") int limit
    ) {
        List<LostItemDTO> items = lostItemService.getLatestLostItems(limit);
        Map<String, Object> response = new HashMap<>();
        response.put("data", items);
        return ResponseEntity.ok(response);
    }
    // 统一封装响应
    private ResponseEntity<Map<String, Object>> wrapResponse(Map<String, Object> response) {
        String status = (String) response.get("status");
        if ("success".equals(status)) {
            return ResponseEntity.ok(response);
        } else {
            String message = (String) response.get("message");
            if (message.contains("无效的用户凭证") || message.contains("用户未认证")) {
                return ResponseEntity.status(401).body(response);
            } else if (message.contains("记录不存在")) {
                return ResponseEntity.status(404).body(response);
            } else {
                return ResponseEntity.status(500).body(response);
            }
        }
    }
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportToExcel(
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String lostLocation,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date lostTime,
            @RequestParam(required = false) String username) {
        try {
            // 根据查询条件获取数据
            List<LostItemDTO> items = lostItemService.fuzzySearch(
                    itemName, lostLocation, lostTime, username
            );

            // 导出为Excel
            ByteArrayOutputStream stream = lostItemService.exportToExcel(items);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String encodedFilename = URLEncoder.encode("失物数据.xlsx", StandardCharsets.UTF_8.name());
            headers.setContentDispositionFormData("attachment", encodedFilename);

            return new ResponseEntity<>(stream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("导出Excel失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    // 新增导入Excel接口
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importFromExcel(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            int count = lostItemService.importFromExcel(file);
            response.put("status", "success");
            response.put("message", "成功导入 " + count + " 条数据");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}